//
//  HTAddSpecialVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/30.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTAddSpecialVC.h"
#import "HTLineCollectionCell.h"
#import "HTCitiesTools.h"
#import "HTMLocationManager.h"

@interface HTAddSpecialVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *startView;
@property (weak, nonatomic) IBOutlet UIView *destinateView;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
@property (weak, nonatomic) IBOutlet UILabel *destinateLabel;
@property (weak, nonatomic) IBOutlet UIImageView *destinateImageView;
@property (weak, nonatomic) IBOutlet UIView *middleView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet UIView *tapBackView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *middleHeight;



@property (nonatomic,strong) HTCitiesTools *citiesTools;

@property (nonatomic,strong) NSArray *provincesData;
@property (nonatomic,strong) NSArray *citiesData;
@property (nonatomic,strong) NSArray *areaData;

@property (nonatomic,strong) NSArray *dataSource;

@property (nonatomic,assign) NSInteger levelCount;

@property (nonatomic,strong) NSString *provincesString;
@property (nonatomic,strong) NSString *cityString;
@property (nonatomic,strong) NSString *areaString;

@property (nonatomic,assign) BOOL isStartOpen;
@property (nonatomic,assign) BOOL isDestiOpen;

@property (nonatomic,strong) NSString *startAddress;
@property (nonatomic,strong) NSString *endAddress;


@end

@implementation HTAddSpecialVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSub];
    [self initData];
    self.title = @"添加订阅路线";
    [self loadLocation];
}
#pragma mark --- 定位
- (void)loadLocation{
    if ([[HTMLocationManager singleInstance] getCurrentAddress].length <= 0) {
        //定位请求
        [self requestLocation];
        self.startLabel.text = @"北京";
    }else{
        self.startLabel.text = [[HTMLocationManager singleInstance] getCurrentAddress];
    }
    self.startAddress = self.startLabel.text;
    self.startLabel.textColor = [UIColor blackColor];
}
- (void)requestLocation{
    [[HTMLocationManager singleInstance]requestLocationCompletionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            if (error.code == AMapLocationErrorLocateFailed)
            {
                [HTShowUtil showMessage:@"定位失败"];
                return;
            }
        }
        if (regeocode)
        {
            if (regeocode.city == nil || regeocode.city.length <= 0) {
                self.startLabel.text = @"北京";
                self.startAddress = self.startLabel.text;
                return;
            }
            [HTMLocationManager singleInstance].currentCity = regeocode.city;
            [HTMLocationManager singleInstance].currentProvince = regeocode.province;
            self.startLabel.text =  [[HTMLocationManager singleInstance]getCurrentAddress];
            self.startAddress = self.startLabel.text;
        }
    }];
}
#pragma mark --- collectionViewDeleagate &dataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HTLineCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:LineCollectionCell forIndexPath:indexPath];
    cell.areaModel = self.dataSource[indexPath.row];
    if (indexPath.row == 0) {
        cell.state = 3;
    }else if (indexPath.row < 4){
        cell.state = 1;
    }else if (indexPath.row % 4 == 0){
        cell.state = 2;
    }else{
        cell.state = 0;
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    HTAreaModel *model = self.dataSource[indexPath.row];
    NSInteger currentIndex = indexPath.row;
    
    switch (model.areaType) {
        case HTAreaTypeNo:
        {
            NSString *terminal = [NSString stringWithFormat:@"%@%@",self.provincesString,self.cityString];
            if (terminal == nil || terminal.length <= 0) {
                terminal = model.title;
            }
            if (self.isStartOpen) {
                self.startLabel.text = terminal;
                self.startAddress = terminal;
                self.isStartOpen = NO;
            }
            if (self.isDestiOpen) {
                self.destinateLabel.text = terminal;
                self.endAddress = terminal;
                self.isDestiOpen = NO;
            }
            self.middleView.hidden = NO;
            self.middleHeight.constant = 100;
            self.bottomView.hidden = YES;
        }
            break;
        case HTAreaTypeProvince:
        {
            self.citiesData = [self.citiesTools loadCitiesDataWithIndex:currentIndex -1];
            self.dataSource = self.citiesData;
            self.levelCount = 1;
            self.provincesString = model.title;
        }
            break;
        case HTAreaTypeDirectCity:
        {
            self.citiesData =[self.citiesTools loadCitiesDataWithIndex:currentIndex - 1];
            self.areaData =[self.citiesTools loadAreasDataWithIndex:currentIndex - 1];
            self.dataSource = self.areaData;
            self.levelCount = 1;
            self.provincesString = model.title;
        }
            break;
        case HTAreaTypeCity:
        {
            self.areaData =[self.citiesTools loadAreasDataWithIndex:currentIndex - 1];
            self.dataSource = self.areaData;
            self.levelCount = 2;
            self.cityString = model.title;
        }
            break;
        case HTAreaTypeArea:
        {
            NSString *terminal = [NSString stringWithFormat:@"%@%@%@",self.provincesString,self.cityString,model.title];
            if (self.isStartOpen) {
                self.startLabel.text = terminal;
                self.startAddress = terminal;
                self.isStartOpen = NO;
            }
            if (self.isDestiOpen) {
                self.destinateLabel.text = terminal;
                self.endAddress = terminal;
                self.isDestiOpen = NO;
            }
            self.middleView.hidden = NO;
            self.middleHeight.constant = 100;
            self.bottomView.hidden = YES;
            
        }
            break;
        default:
            break;
    }
    [collectionView reloadData];
    
}

#pragma mark -- 数据处理
- (void)initData{
    self.citiesTools = [HTCitiesTools shareInstance];
    self.provincesData = [self.citiesTools loadProvincesData];
    self.dataSource = self.provincesData;
    self.levelCount = 0;
    self.isDestiOpen = NO;
    self.isStartOpen = NO;
    [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
    [self setTabViewSelected:NO withImageView:self.destinateImageView withLabel:self.destinateLabel];
}
- (void)reloadInitData{
    self.dataSource = self.provincesData;
    self.provincesString = @"";
    self.cityString = @"";
    self.areaString = @"";
    self.levelCount = 0;
    [self.collectionView reloadData];
}
//点击了返回上一级
- (void)tapBackLevel:(UITapGestureRecognizer *)sender{
    if (self.levelCount == 0) {
        self.levelCount = 0;
        return;
    }else if (self.levelCount == 1){
        self.levelCount = 0;
        self.dataSource = self.provincesData;
        [self.collectionView reloadData];
    }else if (self.levelCount == 2){
        self.dataSource = self.citiesData;
        [self.collectionView reloadData];
        self.levelCount = 1;
    }
}
- (void)setLevelCount:(NSInteger)levelCount{
    _levelCount = levelCount;
    if (levelCount == 0) {
        self.tapBackView.hidden = YES;
    }else{
        self.tapBackView.hidden = NO;
    }
}
- (void)setupSub{
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapBackLevel:)];
    [self.tapBackView addGestureRecognizer:tap1];
    [self.flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.flowLayout.itemSize = CGSizeMake((kHTScreenWidth - kWidth(40))/4, kWidth(44));
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(kWidth(20), kWidth(20), kWidth(20), kWidth(20));
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HTLineCollectionCell" bundle:nil] forCellWithReuseIdentifier:LineCollectionCell];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapPlace:)];
    self.startView.tag = 181;
    [self.startView addGestureRecognizer:tap2];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapPlace:)];
    self.destinateView.tag = 182;
    [self.destinateView addGestureRecognizer:tap3];
    self.middleView.hidden = NO;
    self.middleHeight.constant = 100;
    self.bottomView.hidden = YES;
}
- (void)didTapPlace:(UITapGestureRecognizer *)sender{
    if (sender.view.tag == 181) {//开始
        if (self.isStartOpen) {//关闭
            self.isStartOpen = NO;
            self.middleView.hidden = NO;
            self.middleHeight.constant = 100;
            self.bottomView.hidden = YES;
        }else{//打开
            self.isStartOpen = YES;
            if (self.isDestiOpen) {
                self.isDestiOpen = NO;
            }
            self.bottomView.hidden = NO;
            self.titleLabel.text = @"请选择出发地";
            [self reloadInitData];
            self.middleHeight.constant = 0;
            self.middleView.hidden = YES;
            
        }
       
    }else{//结束
        if (self.isDestiOpen) {//关闭
            self.isDestiOpen = NO;
            self.middleView.hidden = NO;
            self.middleHeight.constant = 100;
            self.bottomView.hidden = YES;
        }else{//打开
            self.isDestiOpen = YES;
            if (self.isStartOpen) {
                self.isStartOpen = NO;
            }
            self.bottomView.hidden = NO;
            [self reloadInitData];
            self.middleHeight.constant = 0;
            self.middleView.hidden = YES;
            self.titleLabel.text = @"请选择目的地";
           
        }
    }
}
- (void)setIsDestiOpen:(BOOL)isDestiOpen{
    _isDestiOpen = isDestiOpen;
    if (isDestiOpen) {
          [self setTabViewSelected:YES withImageView:self.destinateImageView withLabel:self.destinateLabel];
    }else{
          [self setTabViewSelected:NO withImageView:self.destinateImageView withLabel:self.destinateLabel];
    }
}
- (void)setIsStartOpen:(BOOL)isStartOpen{
    _isStartOpen = isStartOpen;
    if (isStartOpen) {
         [self setTabViewSelected:YES withImageView:self.startImageView withLabel:self.startLabel];
    }else{
        [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
    }
    
}
- (void)setTabViewSelected:(BOOL)selected withImageView:(UIImageView *)imageView withLabel:(UILabel *)label{
    if (selected) {
        imageView.image = [[UIImage imageNamed:@"arrow_solid_up"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = kBlueColor;
        label.textColor = kBlueColor;
    }else{
        imageView.image = [[UIImage imageNamed:@"arrow_solid_down"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = [UIColor blackColor];
        label.textColor = [UIColor blackColor];
    }
}

- (IBAction)addOrderAction:(id)sender {
    if (self.startAddress == nil || self.startAddress.length <= 0) {
        [HTShowUtil showMessage:@"请选择出发地"];
        return;
    }
    if (self.endAddress == nil || self.endAddress.length <= 0) {
        [HTShowUtil showMessage:@"请选择目的地"];
        return;
    }
    [self netLoadData];
}
#pragma mark --- 网络请求
- (void)netLoadData{
    [self startHud];
    [HTHttpRequestManager requestOrderlineAddWithFromAddress:self.startAddress withToAddress:self.endAddress success:^(id  _Nullable responseObject) {
         [self endHud];
        DBLog(@"订阅添加：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"添加订阅请求失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
         [HTShowUtil showMessage:responseObject[@"message"]];
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSError * _Nonnull error) {
          [self endHud];
    }];
   
}

@end
